#!/bin/sh
#
# /etc/rc.d/rc.ferm
#
# To make ferm automatically apply rules at boot, make this
# file executable:  chmod 755 /etc/rc.d/rc.ferm

CONFIG_FILE=/etc/ferm.conf
RUN_FILE=/var/run/ferm.run
FERM=/usr/sbin/ferm

set -eE

log_err()
{
	>&2 echo "$1" 
}

check_cfg()
{
	if [ ! -e "$CONFIG_FILE" ]
	then
		log_err "required config file $CONFIG_FILE missing!"
		return 1
	fi
}
service_start()
{
	if [ ! -e "$RUN_FILE" ]
	then
		"$FERM" "$CONFIG_FILE"
	else
		log_err "ferm rules seem to have been already been applied ($RUN_FILE present). Aborting"
		return 1
	fi

}

service_stop()
{
	if [ -e "$RUN_FILE" ]
	then
		"$FERM" -F "$CONFIG_FILE"
	else
		log_err "Could not find $RUN_FILE to assess if ferm was service_started. Aborting"
		return 1
	fi
}


case "$1" in
	'start')
		if service_start
		then
			touch "$RUN_FILE"
		else
			log_err "Error starting service"
			exit 1
		fi
		;;
	'stop')
		if service_stop
		then
			rm -f "$RUN_FILE"
		else
			log_err "Error stopping service"
			exit 1
		fi
		;;
	'restart')
		service_stop && service_start
		;;
	*)
		echo "Usage: $0 {start|stop|restart}"
		;;
esac

